import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Modal,
  Form,
  Select,
  Tree,
  Tag,
  Toast,
  Typography,
  Row,
  Col,
  Tabs,
  TabPane,
} from '@douyinfe/semi-ui';
import {
  IconPlus,
  IconSearch,
  IconEdit,
  IconRefresh,
  IconUser,
  IconUserGroup,
} from '@douyinfe/semi-icons';
import { menuApi, SysMenu } from '../../api/menu';
import MenuPermissionAssignment from '../../components/MenuPermissionAssignment';

const { Title } = Typography;
const { Column } = Table;

interface User {
  id: number;
  username: string;
  nickname: string;
  email: string;
  status: number;
}

interface Role {
  id: number;
  roleName: string;
  roleCode: string;
  description: string;
  status: number;
}

const PermissionAssignment: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [userKeyword, setUserKeyword] = useState('');
  const [roleKeyword, setRoleKeyword] = useState('');
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [assignmentTarget, setAssignmentTarget] = useState<{
    type: 'user' | 'role';
    id: number;
    name: string;
  } | null>(null);

  useEffect(() => {
    loadUsers();
    loadRoles();
  }, []);

  const loadUsers = async () => {
    try {
      setLoading(true);
      // 这里应该调用用户API
      const response = await fetch('/system/users');
      if (response.ok) {
        const data = await response.json();
        setUsers(data.data || []);
      }
    } catch (error) {
      console.error('加载用户失败:', error);
      Toast.error('加载用户失败');
    } finally {
      setLoading(false);
    }
  };

  const loadRoles = async () => {
    try {
      setLoading(true);
      // 这里应该调用角色API
      const response = await fetch('/system/roles');
      if (response.ok) {
        const data = await response.json();
        setRoles(data.data || []);
      }
    } catch (error) {
      console.error('加载角色失败:', error);
      Toast.error('加载角色失败');
    } finally {
      setLoading(false);
    }
  };

  const handleUserSearch = () => {
    // 实现用户搜索逻辑
    loadUsers();
  };

  const handleRoleSearch = () => {
    // 实现角色搜索逻辑
    loadRoles();
  };

  const handleAssignUserPermission = (user: User) => {
    setAssignmentTarget({
      type: 'user',
      id: user.id,
      name: user.nickname || user.username,
    });
    setPermissionModalVisible(true);
  };

  const handleAssignRolePermission = (role: Role) => {
    setAssignmentTarget({
      type: 'role',
      id: role.id,
      name: role.roleName,
    });
    setPermissionModalVisible(true);
  };

  const handlePermissionAssignmentClose = () => {
    setPermissionModalVisible(false);
    setAssignmentTarget(null);
  };

  const userColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => handleAssignUserPermission(record)}
          >
            分配权限
          </Button>
        </Space>
      ),
    },
  ];

  const roleColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '角色代码',
      dataIndex: 'roleCode',
      key: 'roleCode',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => handleAssignRolePermission(record)}
          >
            分配权限
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title heading={3}>权限分配管理</Title>
      
      <Tabs type="line" defaultActiveKey="users">
        <TabPane tab={<span><IconUser />用户权限</span>} itemKey="users">
          <Card>
            <div style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Input
                    placeholder="搜索用户名或昵称"
                    value={userKeyword}
                    onChange={setUserKeyword}
                    suffix={<IconSearch />}
                  />
                </Col>
                <Col span={16}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<IconSearch />}
                      onClick={handleUserSearch}
                    >
                      搜索
                    </Button>
                    <Button
                      icon={<IconRefresh />}
                      onClick={() => {
                        setUserKeyword('');
                        loadUsers();
                      }}
                    >
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
            </div>
            
            <Table
              columns={userColumns}
              dataSource={users}
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
              }}
              rowKey="id"
            />
          </Card>
        </TabPane>
        
        <TabPane tab={<span><IconUserGroup />角色权限</span>} itemKey="roles">
          <Card>
            <div style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Input
                    placeholder="搜索角色名称或代码"
                    value={roleKeyword}
                    onChange={setRoleKeyword}
                    suffix={<IconSearch />}
                  />
                </Col>
                <Col span={16}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<IconSearch />}
                      onClick={handleRoleSearch}
                    >
                      搜索
                    </Button>
                    <Button
                      icon={<IconRefresh />}
                      onClick={() => {
                        setRoleKeyword('');
                        loadRoles();
                      }}
                    >
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
            </div>
            
            <Table
              columns={roleColumns}
              dataSource={roles}
              loading={loading}
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
              }}
              rowKey="id"
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 权限分配弹窗 */}
      {assignmentTarget && (
        <MenuPermissionAssignment
          visible={permissionModalVisible}
          targetType={assignmentTarget.type}
          targetId={assignmentTarget.id}
          targetName={assignmentTarget.name}
          onClose={handlePermissionAssignmentClose}
          onSuccess={() => {
            Toast.success('权限分配成功');
            handlePermissionAssignmentClose();
          }}
        />
      )}
    </div>
  );
};

export default PermissionAssignment;